package cn.xlbweb.cli.service.impl;

import cn.xlbweb.cli.mapper.RoleMapper;
import cn.xlbweb.cli.pojo.dto.RoleInsertDTO;
import cn.xlbweb.cli.pojo.dto.RoleListDTO;
import cn.xlbweb.cli.pojo.dto.RoleUpdateDTO;
import cn.xlbweb.cli.service.RoleService;
import cn.xlbweb.util.res.ResponseServer;
import cn.xlbweb.util.res.ResponseTable;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author: bobi
 * @date: 2019-02-11 16:02
 * @description:
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public ResponseServer getRole(Integer id) {
        Map<String, Object> result = roleMapper.getRole(id);
        if (!CollectionUtils.isEmpty(result)) {
            return ResponseServer.success(result);
        }
        return ResponseServer.error("角色不存在");
    }

    @Override
    public ResponseTable listRole(RoleListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getSize());
        List<Map<String, Object>> results = roleMapper.listRole(dto);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(results);
        return ResponseTable.success(pageInfo.getTotal(), results);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer insertRole(RoleInsertDTO dto) {
        int count = roleMapper.insertRole(dto);
        if (count > 0) {
            return ResponseServer.success();
        }
        return ResponseServer.error("插入角色失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer updateRole(RoleUpdateDTO dto) {
        int count = roleMapper.updateRole(dto);
        if (count > 0) {
            return ResponseServer.success();
        }
        return ResponseServer.error("更新角色失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseServer deleteRole(String ids) {
        int count = roleMapper.deleteRole(ids);
        if (count > 0) {
            return ResponseServer.success();
        }
        return ResponseServer.error("删除角色失败");
    }
}
